package com.bjut.vendormgrsys.service.impl;

import com.bjut.vendormgrsys.util.DateUtils;
import lombok.extern.java.Log;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Log
@Service
public class FileUtilService {

    public String uploadFile(MultipartFile file, String type){
        String date = DateUtils.formatDate((new Date()).getTime(), DateUtils.Pattern.PATTERN_ONLY_DATE);
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);

        //文件上传路径
        String filePath = System.getProperty("user.dir") + "\\uploadFile\\"+ date + "\\" + type + "\\" + fileSuffix + "\\" + DateUtils.now() + fileName;
        File dest = new File(filePath);

        //检测目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        boolean flag = true;
        String path=null;
        try {
            file.transferTo(dest);
            path = dest.getPath();  //得到文件路径
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
        }
        if(!flag){
            throw new RuntimeException("文件保存失败");
        }

        return path;
    }

    public void delFile(String path){
        if(path==null||path.equals("")){
            return;
        }
        File file = new File(path);

        if(file.exists() && file.isFile()){
            file.delete();
        }
    }
}
